package com.daxue.lcm.api.grpc.config;

import com.daxue.lcm.api.grpc.client.DynamicLoadingGrpcServiceClient;
import com.daxue.lcm.api.grpc.properties.GrpcServiceProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

import static com.daxue.lcm.api.grpc.properties.GrpcServiceProperties.DISABLE_SERVICE;
import static com.daxue.lcm.api.grpc.properties.GrpcServiceProperties.ENABLED;
import static com.daxue.lcm.api.grpc.properties.GrpcServiceProperties.SERVICE_PREFIX;

/**
 * @author daxue0929
 * @date 2022/9/28
 */

@Configuration
@EnableConfigurationProperties(GrpcServiceProperties.class)
public class EnableGrpcServiceConfiguration {


    @Bean("testMap")
    public HashMap<String, Object> hashMap() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("test", "testValue");
        return hashMap;
    }


    @Configuration
    @ConditionalOnMissingBean(DynamicLoadingGrpcServiceClient.class)
    public static class DynamicLoadingGrpcServiceConfiguration
        extends AbstractGrpcServiceConfiguration<DynamicLoadingGrpcServiceClient> {

        @Bean("dynamicLoadingGrpcServiceClient")
        @ConditionalOnProperty(prefix = SERVICE_PREFIX + DynamicLoadingGrpcServiceClient.SERVICE_NAME, name = ENABLED,
            havingValue = DISABLE_SERVICE)
        public DynamicLoadingGrpcServiceClient inProcessDynamicLoadingGrpcServiceClient(
            final GrpcServiceProperties grpcServiceProperties
        ) {
            return instantiate(grpcServiceProperties.getService().get(DynamicLoadingGrpcServiceClient.SERVICE_NAME));
        }

        @Bean
        @ConditionalOnProperty(prefix = SERVICE_PREFIX + DynamicLoadingGrpcServiceClient.SERVICE_NAME, name = ENABLED)
        public DynamicLoadingGrpcServiceClient dautoynamicLoadingGrpcServiceClientByAddress(
            final GrpcServiceProperties grpcServiceProperties) {
            GrpcServiceInfo grpcServiceInfo = grpcServiceProperties.getService()
                .get(DynamicLoadingGrpcServiceClient.SERVICE_NAME);
            DynamicLoadingGrpcServiceClient instantiate = instantiate(grpcServiceInfo);
            return instantiate;
        }

        @Override
        protected DynamicLoadingGrpcServiceClient instantiate(GrpcServiceInfo grpcServiceInfo) {
            return new DynamicLoadingGrpcServiceClient(
                genChannel(DynamicLoadingGrpcServiceClient.SERVICE_NAME, grpcServiceInfo), grpcServiceInfo);
        }
    }




}
